package lab.anoper.juc.threadlocal;

import java.util.UUID;

/**
 * @author 闫家洪（yanjiahong@vcredit.com）
 * @since 2024/12/12
 */
public class LoggerDemo {
    static class LogSettings {
        private String logLevel;
        private String requestId;
        private boolean isDebugging;
    }

    static class Logger {
        private final ThreadLocal<LogSettings> logSettingsTl = ThreadLocal.withInitial(() -> null);

        public void setLogLevel(String logLevel) {
            createSettingsIfAbsent();
            logSettingsTl.get().logLevel = logLevel;
        }

        public void setRequestId(String requestId) {
            createSettingsIfAbsent();
            logSettingsTl.get().requestId = requestId;
        }

        public void setDebugging(boolean debugging) {
            createSettingsIfAbsent();
            logSettingsTl.get().isDebugging = debugging;
        }

        public void log(String msg) {
            System.out.printf("[%s] [%s] [%s] [%s] %s|\r\n", Thread.currentThread().getName(), getLogLevel(),
                    getRequestId(), isDebugging(), msg);
        }

        public String getLogLevel() {
            return getLogSettings().logLevel;
        }

        public String getRequestId() {
            return getLogSettings().requestId;
        }

        public boolean isDebugging() {
            return getLogSettings().isDebugging;
        }

        private void createSettingsIfAbsent() {
            LogSettings settings = logSettingsTl.get();
            if (settings == null) {
                settings = new LogSettings();
                logSettingsTl.set(settings);
            }
        }

        public LogSettings getLogSettings() {
            LogSettings settings = logSettingsTl.get();
            if (settings == null) {
                settings = new LogSettings();
                logSettingsTl.set(settings);
            }
            return settings;
        }
    }

    public static void main(String[] args) {
        Logger logger = new Logger();
        new Thread(() -> {

        }).start();
        new Thread(() -> {
            logger.setLogLevel("INFO");
            logger.setRequestId(UUID.randomUUID().toString());
            logger.setDebugging(false);

            logger.log("这是第一个线程");
        }).start();
        new Thread(() -> {
            logger.setLogLevel("ERROR");
            logger.setRequestId(UUID.randomUUID().toString());
            logger.setDebugging(true);

            logger.log("你好");
        }).start();
    }

}
